<template>
  <el-dialog
    :title="dialogTitle"
    :visible="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="setting-content" v-if="slotNumber">
      <div class="setting-header">
        <span class="slot-info">
          <span class="info-label">工段号:</span>
          <span class="info-value highlight">{{ sectionName || '-' }}</span>
          <span class="info-separator">|</span>
          <span class="info-label">槽位编号:</span>
          <span class="info-value highlight">{{ slotNumber }}</span>
          <span class="info-separator">|</span>
          <span class="info-label">点位/缸数:</span>
          <span class="info-value highlight">{{ pointsPerSlot }}</span>
        </span>
      </div>

      <table class="setting-table">
        <!-- 动作设置 -->
        <tr class="setting-row">
          <td class="setting-title-cell">
            <span class="setting-title">动作</span>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">点位：</span>
              <el-select v-model="settings[0].positionNumber" placeholder="选择点位" size="small" style="width: 120px">
                <el-option 
                  v-for="pos in positionOptions" 
                  :key="pos.value" 
                  :label="pos.label" 
                  :value="pos.value"
                />
              </el-select>
            </div>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">动作类型：</span>
              <el-radio-group v-model="settings[0].actionType" size="small">
                <el-radio :label="0">打壳</el-radio>
                <el-radio :label="1">下料</el-radio>
              </el-radio-group>
            </div>
          </td>
          <td class="setting-action-cell">
            <el-button 
              type="primary" 
              size="small" 
              @click="saveSetting(0)"
              :loading="savingIndex === 0"
              icon="el-icon-check"
            >
              设置
            </el-button>
          </td>
        </tr>

        <!-- 打壳时间设置 -->
        <tr class="setting-row">
          <td class="setting-title-cell">
            <span class="setting-title">打壳时间</span>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">点位：</span>
              <el-select 
                v-model="settings[1].positionNumber" 
                placeholder="选择点位" 
                size="small" 
                style="width: 120px"
                @change="onPositionChange(1)"
              >
                <el-option 
                  v-for="pos in positionOptions" 
                  :key="pos.value" 
                  :label="pos.label" 
                  :value="pos.value"
                />
              </el-select>
            </div>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">打壳时间(秒)：</span>
              <el-input-number 
                v-model="settings[1].strikeTime" 
                :precision="1" 
                :step="0.1" 
                :min="0" 
                :max="25.5"
                size="small"
                style="width: 120px"
              />
            </div>
          </td>
          <td class="setting-action-cell">
            <el-button 
              type="primary" 
              size="small" 
              @click="saveSetting(1)"
              :loading="savingIndex === 1"
              icon="el-icon-check"
            >
              设置
            </el-button>
          </td>
        </tr>
        <!-- 打壳时间当前值显示 -->
        <tr class="timing-display-row" v-if="slotTimingData">
          <td class="setting-title-cell"></td>
          <td colspan="3" class="timing-values-cell">
            <div class="timing-values-wrapper">
              <span class="timing-label">
                <i class="el-icon-time"></i>
                当前值：
              </span>
              <div class="timing-items-container">
                <span 
                  v-for="i in pointsPerSlot" 
                  :key="i" 
                  class="timing-item"
                >
                  <span class="timing-position">点位{{ i }}</span>
                  <span class="timing-separator">:</span>
                  <span class="timing-value">{{ getStrikeTime(i) || '-' }}</span>
                  <span class="timing-unit">秒</span>
                </span>
              </div>
            </div>
          </td>
        </tr>

        <!-- 换极阶段1设置 -->
        <tr class="setting-row">
          <td class="setting-title-cell">
            <span class="setting-title">换极阶段1</span>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">点位：</span>
              <el-select 
                v-model="settings[2].positionNumber" 
                placeholder="选择点位" 
                size="small" 
                style="width: 120px"
                @change="onPositionChange(2)"
              >
                <el-option 
                  v-for="pos in positionOptions" 
                  :key="pos.value" 
                  :label="pos.label" 
                  :value="pos.value"
                />
              </el-select>
            </div>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">阶段时间(分钟)：</span>
              <el-input-number 
                v-model="settings[2].poleChangeStage1Time" 
                :min="0" 
                :max="255"
                size="small"
                style="width: 120px"
              />
            </div>
          </td>
          <td class="setting-action-cell">
            <el-button 
              type="primary" 
              size="small" 
              @click="saveSetting(2)"
              :loading="savingIndex === 2"
              icon="el-icon-check"
            >
              设置
            </el-button>
          </td>
        </tr>
        <!-- 换极阶段1当前值显示 -->
        <tr class="timing-display-row" v-if="slotTimingData">
          <td class="setting-title-cell"></td>
          <td colspan="3" class="timing-values-cell">
            <div class="timing-values-wrapper">
              <span class="timing-label">
                <i class="el-icon-time"></i>
                当前值：
              </span>
              <div class="timing-items-container">
                <span 
                  v-for="i in pointsPerSlot" 
                  :key="i" 
                  class="timing-item"
                >
                  <span class="timing-position">点位{{ i }}</span>
                  <span class="timing-separator">:</span>
                  <span class="timing-value">{{ getStage1Time(i) || '-' }}</span>
                  <span class="timing-unit">分钟</span>
                </span>
              </div>
            </div>
          </td>
        </tr>

        <!-- 换极阶段2设置 -->
        <tr class="setting-row">
          <td class="setting-title-cell">
            <span class="setting-title">换极阶段2</span>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">点位：</span>
              <el-select 
                v-model="settings[3].positionNumber" 
                placeholder="选择点位" 
                size="small" 
                style="width: 120px"
                @change="onPositionChange(3)"
              >
                <el-option 
                  v-for="pos in positionOptions" 
                  :key="pos.value" 
                  :label="pos.label" 
                  :value="pos.value"
                />
              </el-select>
            </div>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">阶段时间(分钟)：</span>
              <el-input-number 
                v-model="settings[3].poleChangeStage2Time" 
                :min="0" 
                :max="255"
                size="small"
                style="width: 120px"
              />
            </div>
          </td>
          <td class="setting-action-cell">
            <el-button 
              type="primary" 
              size="small" 
              @click="saveSetting(3)"
              :loading="savingIndex === 3"
              icon="el-icon-check"
            >
              设置
            </el-button>
          </td>
        </tr>
        <!-- 换极阶段2当前值显示 -->
        <tr class="timing-display-row" v-if="slotTimingData">
          <td class="setting-title-cell"></td>
          <td colspan="3" class="timing-values-cell">
            <div class="timing-values-wrapper">
              <span class="timing-label">
                <i class="el-icon-time"></i>
                当前值：
              </span>
              <div class="timing-items-container">
                <span 
                  v-for="i in pointsPerSlot" 
                  :key="i" 
                  class="timing-item"
                >
                  <span class="timing-position">点位{{ i }}</span>
                  <span class="timing-separator">:</span>
                  <span class="timing-value">{{ getStage2Time(i) || '-' }}</span>
                  <span class="timing-unit">分钟</span>
                </span>
              </div>
            </div>
          </td>
        </tr>

        <!-- 自动换极号设置 -->
        <tr class="setting-row">
          <td class="setting-title-cell">
            <span class="setting-title">手动换极号</span>
          </td>
          <td class="setting-form-cell">
            <div class="form-item-compact">
              <span class="item-label">换极号：</span>
              <el-select v-model="settings[4].autoPoleNumber" placeholder="选择换极号" size="small" style="width: 150px">
                <el-option 
                  v-for="pole in poleNumberOptions" 
                  :key="pole.value" 
                  :label="pole.label" 
                  :value="pole.value"
                />
              </el-select>
            </div>
          </td>
          <td class="setting-form-cell"></td>
          <td class="setting-action-cell">
            <el-button 
              type="primary" 
              size="small" 
              @click="saveSetting(4)"
              :loading="savingIndex === 4"
              icon="el-icon-check"
            >
              设置
            </el-button>
          </td>
        </tr>
      </table>
    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveSlotSetting, getSlotTiming } from "@/api/workshop/section";

export default {
  name: 'SlotSettingDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    slotNumber: {
      type: Number,
      default: null
    },
    pointsPerSlot: {
      type: Number,
      default: 4,
      validator(value) {
        return value >= 1 && value <= 6;
      }
    },
    sectionName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      savingIndex: -1,
      loadingTiming: false,
      // 槽位时间设置数据
      slotTimingData: null,
      // 指令类型：0-动作, 1-打壳时间, 2-换极阶段1, 3-换极阶段2, 4-自动换极号
      settings: [
        { commandType: 0, positionNumber: 1, actionType: 0 }, // 动作
        { commandType: 1, positionNumber: 1, strikeTime: 0 }, // 打壳时间
        { commandType: 2, positionNumber: 1, poleChangeStage1Time: 0 }, // 换极阶段1
        { commandType: 3, positionNumber: 1, poleChangeStage2Time: 0 }, // 换极阶段2
        { commandType: 4, positionNumber: 0, autoPoleNumber: 'A1' } // 自动换极号（点位号为0，无意义）
      ]
    };
  },
  computed: {
    /** 对话框标题 */
    dialogTitle() {
      if (this.slotNumber) {
        return `槽位设置 - 槽位${this.slotNumber}`;
      }
      return '槽位设置';
    },
    /** 根据实际点位数动态生成点位选项 */
    positionOptions() {
      const options = [];
      for (let i = 1; i <= this.pointsPerSlot; i++) {
        options.push({ label: `点位${i}`, value: i });
      }
      return options;
    },
    /** 根据工段名称动态生成换极号选项 */
    poleNumberOptions() {
      const options = [];
      // 根据工段判断换极号范围
      // 对于11、12、21、22、31、32、41、42段：A1到A10，B1到B10
      // 对于51、52、61、62段：A1到A12，B1到B12
      const sectionName = this.sectionName || '';
      let maxNumber = 10; // 默认最大值
      
      // 判断是否为51、52、61、62段
      if (sectionName === '51段' || sectionName === '52段' || 
          sectionName === '61段' || sectionName === '62段') {
        maxNumber = 12;
      }
      
      // 生成A系列选项
      for (let i = 1; i <= maxNumber; i++) {
        options.push({ label: `A${i}`, value: `A${i}` });
      }
      
      // 生成B系列选项
      for (let i = 1; i <= maxNumber; i++) {
        options.push({ label: `B${i}`, value: `B${i}` });
      }
      
      return options;
    },
    // 计算属性：打壳时间设置的点位（用于watch，避免数组索引路径问题）
    strikePositionNumber() {
      return this.settings[1] ? this.settings[1].positionNumber : null;
    },
    // 计算属性：换极阶段1设置的点位
    stage1PositionNumber() {
      return this.settings[2] ? this.settings[2].positionNumber : null;
    },
    // 计算属性：换极阶段2设置的点位
    stage2PositionNumber() {
      return this.settings[3] ? this.settings[3].positionNumber : null;
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal;
      if (newVal && this.slotNumber) {
        // 对话框打开时加载槽位时间设置
        this.loadSlotTiming();
      } else if (!newVal) {
        // 对话框关闭时清空数据
        this.slotTimingData = null;
      }
    },
    // 监听打壳时间设置的点位变化（使用computed属性，避免数组索引路径问题）
    strikePositionNumber(newVal) {
      this.$nextTick(() => {
        if (newVal && this.slotTimingData) {
          const strikeTime = this.getStrikeTimeValue(newVal);
          this.$set(this.settings[1], 'strikeTime', strikeTime !== null ? strikeTime : 0);
        } else if (newVal && !this.slotTimingData) {
          this.$set(this.settings[1], 'strikeTime', 0);
        }
      });
    },
    // 监听换极阶段1设置的点位变化
    stage1PositionNumber(newVal) {
      this.$nextTick(() => {
        if (newVal && this.slotTimingData) {
          const stage1Time = this.getStage1Time(newVal);
          this.$set(this.settings[2], 'poleChangeStage1Time', stage1Time !== null ? stage1Time : 0);
        } else if (newVal && !this.slotTimingData) {
          this.$set(this.settings[2], 'poleChangeStage1Time', 0);
        }
      });
    },
    // 监听换极阶段2设置的点位变化
    stage2PositionNumber(newVal) {
      this.$nextTick(() => {
        if (newVal && this.slotTimingData) {
          const stage2Time = this.getStage2Time(newVal);
          this.$set(this.settings[3], 'poleChangeStage2Time', stage2Time !== null ? stage2Time : 0);
        } else if (newVal && !this.slotTimingData) {
          this.$set(this.settings[3], 'poleChangeStage2Time', 0);
        }
      });
    },
    // 监听时间数据加载完成
    slotTimingData(newVal) {
      if (newVal) {
        // 时间数据加载完成后，更新当前选择点位的值
        this.updateCurrentValues();
      }
    }
  },
  methods: {
    /** 关闭对话框 */
    handleClose() {
      this.dialogVisible = false;
      this.$emit('update:visible', false);
      // 清空时间数据
      this.slotTimingData = null;
    },
    /** 加载槽位时间设置 */
    async loadSlotTiming() {
      if (!this.slotNumber) {
        return;
      }
      
      this.loadingTiming = true;
      try {
        const response = await getSlotTiming(this.slotNumber);
        if (response.code === 200 && response.data) {
          this.slotTimingData = response.data;
        } else {
          // 静默失败，不显示错误信息
          this.slotTimingData = null;
        }
      } catch (error) {
        // 静默失败，不显示错误信息
        this.slotTimingData = null;
      } finally {
        this.loadingTiming = false;
      }
    },
    /** 获取指定点位的打壳时间（用于显示） */
    getStrikeTime(positionNumber) {
      if (!this.slotTimingData || !this.slotTimingData.positionTimings) {
        return null;
      }
      const timing = this.slotTimingData.positionTimings.find(
        pt => pt.positionNumber === positionNumber
      );
      return timing && timing.strikeTimeSeconds !== null 
        ? timing.strikeTimeSeconds.toFixed(1) 
        : null;
    },
    /** 获取指定点位的打壳时间（原始数值，用于输入框） */
    getStrikeTimeValue(positionNumber) {
      if (!this.slotTimingData || !this.slotTimingData.positionTimings) {
        return null;
      }
      const timing = this.slotTimingData.positionTimings.find(
        pt => pt.positionNumber === positionNumber
      );
      return timing && timing.strikeTimeSeconds !== null 
        ? timing.strikeTimeSeconds 
        : null;
    },
    /** 获取指定点位的阶段1时间 */
    getStage1Time(positionNumber) {
      if (!this.slotTimingData || !this.slotTimingData.positionTimings) {
        return null;
      }
      const timing = this.slotTimingData.positionTimings.find(
        pt => pt.positionNumber === positionNumber
      );
      return timing && timing.stage1Minutes !== null 
        ? timing.stage1Minutes 
        : null;
    },
    /** 获取指定点位的阶段2时间 */
    getStage2Time(positionNumber) {
      if (!this.slotTimingData || !this.slotTimingData.positionTimings) {
        return null;
      }
      const timing = this.slotTimingData.positionTimings.find(
        pt => pt.positionNumber === positionNumber
      );
      return timing && timing.stage2Minutes !== null 
        ? timing.stage2Minutes 
        : null;
    },
    /** 处理点位选择变化 */
    onPositionChange(settingIndex) {
      if (!this.slotTimingData) {
        return;
      }
      
      const setting = this.settings[settingIndex];
      const positionNumber = setting.positionNumber;
      
      if (!positionNumber) {
        return;
      }
      
      switch (settingIndex) {
        case 1: // 打壳时间
          const strikeTime = this.getStrikeTimeValue(positionNumber);
          this.$set(this.settings[1], 'strikeTime', strikeTime !== null ? strikeTime : 0);
          break;
        case 2: // 换极阶段1
          const stage1Time = this.getStage1Time(positionNumber);
          this.$set(this.settings[2], 'poleChangeStage1Time', stage1Time !== null ? stage1Time : 0);
          break;
        case 3: // 换极阶段2
          const stage2Time = this.getStage2Time(positionNumber);
          this.$set(this.settings[3], 'poleChangeStage2Time', stage2Time !== null ? stage2Time : 0);
          break;
      }
    },
    /** 更新当前选择点位的值 */
    updateCurrentValues() {
      if (!this.slotTimingData) {
        return;
      }
      
      // 更新打壳时间
      if (this.settings[1].positionNumber) {
        const strikeTime = this.getStrikeTimeValue(this.settings[1].positionNumber);
        this.$set(this.settings[1], 'strikeTime', strikeTime !== null ? strikeTime : 0);
      }
      
      // 更新换极阶段1时间
      if (this.settings[2].positionNumber) {
        const stage1Time = this.getStage1Time(this.settings[2].positionNumber);
        this.$set(this.settings[2], 'poleChangeStage1Time', stage1Time !== null ? stage1Time : 0);
      }
      
      // 更新换极阶段2时间
      if (this.settings[3].positionNumber) {
        const stage2Time = this.getStage2Time(this.settings[3].positionNumber);
        this.$set(this.settings[3], 'poleChangeStage2Time', stage2Time !== null ? stage2Time : 0);
      }
    },
    /** 设置设置 */
    async saveSetting(index) {
      if (!this.slotNumber) {
        this.$message.warning('槽位编号无效');
        return;
      }

      const setting = this.settings[index];
      
      // 构建请求数据
      const requestData = {
        businessSlotNo: this.slotNumber,
        commandType: setting.commandType,
        positionNumber: setting.positionNumber || 0 // 自动换极号使用0（预留）
      };
      
      // 对于非自动换极号的指令，验证点位
      if (setting.commandType !== 4) {
        if (setting.positionNumber === null || setting.positionNumber === undefined || setting.positionNumber === 0) {
          this.$message.warning('请选择点位');
          return;
        }
      }

      // 根据指令类型设置相应的数据字段
      switch (setting.commandType) {
        case 0: // 动作
          if (setting.actionType === null || setting.actionType === undefined) {
            this.$message.warning('请选择动作类型');
            return;
          }
          requestData.actionType = setting.actionType;
          break;
        case 1: // 打壳时间
          if (setting.strikeTime === null || setting.strikeTime === undefined) {
            this.$message.warning('请输入打壳时间');
            return;
          }
          requestData.strikeTime = setting.strikeTime;
          break;
        case 2: // 换极阶段1
          if (setting.poleChangeStage1Time === null || setting.poleChangeStage1Time === undefined) {
            this.$message.warning('请输入阶段1时间');
            return;
          }
          requestData.poleChangeStage1Time = setting.poleChangeStage1Time;
          break;
        case 3: // 换极阶段2
          if (setting.poleChangeStage2Time === null || setting.poleChangeStage2Time === undefined) {
            this.$message.warning('请输入阶段2时间');
            return;
          }
          requestData.poleChangeStage2Time = setting.poleChangeStage2Time;
          break;
        case 4: // 自动换极号
          if (!setting.autoPoleNumber) {
            this.$message.warning('请选择换极号');
            return;
          }
          requestData.autoPoleNumber = setting.autoPoleNumber;
          break;
      }

      this.savingIndex = index;
      try {
        const response = await saveSlotSetting(requestData);
        if (response.code === 200) {
          this.$message.success('设置设置成功');
          // 设置成功后刷新时间数据
          if (setting.commandType === 1 || setting.commandType === 2 || setting.commandType === 3) {
            this.loadSlotTiming();
          }
        } else {
          this.$message.error(response.msg || '设置设置失败');
        }
      } catch (error) {
        this.$message.error('设置设置失败: ' + (error.message || '未知错误'));
      } finally {
        this.savingIndex = -1;
      }
    }
  }
}
</script>

<style scoped>
.setting-content {
  max-height: 600px;
  overflow-y: auto;
  padding: 10px 0;
}

.setting-header {
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.slot-info {
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.info-label {
  color: #606266;
  font-weight: normal;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

.info-value.highlight {
  color: #409eff;
  font-weight: bold;
  font-size: 15px;
}

.info-separator {
  color: #c0c4cc;
  margin: 0 4px;
}

.timing-display-row {
  background-color: #f5f7fa;
}

.timing-display-row td {
  padding: 10px 8px;
  font-size: 13px;
  vertical-align: middle;
}

.timing-values-cell {
  padding-left: 130px !important;
}

.timing-values-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  width: 100%;
}

.timing-label {
  color: #909399;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
  margin-right: 4px;
}

.timing-label i {
  font-size: 16px;
  color: #409eff;
}

.timing-items-container {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: nowrap;
  flex: 1;
  overflow: hidden;
}

.timing-item {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  gap: 1px;
  flex-shrink: 0;
}

.timing-position {
  color: #606266;
  font-weight: 500;
}

.timing-separator {
  color: #c0c4cc;
  margin: 0;
}

.timing-value {
  color: #409eff;
  font-weight: bold;
  font-size: 15px;
  min-width: 22px;
  text-align: center;
  display: inline-block;
}

.timing-unit {
  color: #909399;
  font-size: 13px;
  margin-left: 0;
}

.setting-table {
  width: 100%;
  border-collapse: collapse;
  border: none;
}

.setting-table td {
  border: none;
  padding: 10px 8px;
  vertical-align: middle;
}

.setting-row {
  border-bottom: 1px solid #f0f0f0;
}

.setting-row:last-child {
  border-bottom: none;
}

.setting-title-cell {
  width: 130px;
  text-align: left;
}

.setting-form-cell {
  width: auto;
  text-align: left;
  padding-left: 10px;
}

.setting-action-cell {
  width: 100px;
  text-align: right;
  padding-right: 0;
}

.setting-title {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
}

.form-item-compact {
  display: flex;
  align-items: center;
  gap: 6px;
}

.item-label {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style>
